﻿using RightControl.IService;
using RightControl.Model;
using RightControl.WebApp.Areas.Admin.Controllers;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace RightControl.WebApp.Areas.DataSrv.Controllers
{
    public class CommonDataController : BaseController
    {
        public static ITranslationService tranService { get; set; }

        // GET: DataSrv/CommonData
        public  ActionResult Index(int? id) 
        {
            return View();
        }


        [HttpPost]
        public ActionResult Index(Translation model) {
            bool updateFlag = false;
            if (model!=null) {
                string[] oriContentArray = model.OriContent.Split(new string[] { "\r\n" }, StringSplitOptions.None);
                string[] contentEng = model.TransEnglish.Split(new string[] { "\r\n" }, StringSplitOptions.None);
                if (oriContentArray != null && contentEng != null && oriContentArray.Length == contentEng.Length) {
                    HashSet<string> words = new HashSet<string>(oriContentArray);
                    Dictionary<string, Translation> wordsRet = tranService.GetWordsTranslation(words);                    

                    for (int i = 0; i < oriContentArray.Length; i++) {
                        model.OriContent = oriContentArray[i].Trim(' ');
                        model.TransEnglish = contentEng[i].Trim(' ');
                        model.CreateOn = DateTime.Now;
                        model.CreateBy = Operator.UserId;
                        model.UpdateBy = Operator.UserId;
                        if (wordsRet.ContainsKey(model.OriContent)) {
                            model.Id = wordsRet[model.OriContent].Id;
                            updateFlag = tranService.UpdateModel(model);
                        }
                        else {
                            updateFlag = tranService.InsertModel(model) > 0;
                        }                   
                    }

                    ViewBag.Msg = updateFlag ? "保存成功！" : "保存失败!";
                }
                else {
                    ViewBag.Msg = "保存失败,数据有误,请检查后重试!";
                }
            }
        
            return View(model);
        }

    }
}